package com.tarena.charging.cost.repository;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tarena.charging.cost.mapper.CostRuleMapper;
import com.tarena.charging.cost.pojo.po.CostRulePO;
import java.util.List;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Repository;

@Repository
@Slf4j
public class CostRuleRepository {
    @Autowired
    private CostRuleMapper costRuleMapper;
    @Autowired
    private RedisTemplate redisTemplate;

    public List<CostRulePO> getCostRulesByStationIdAndGunId(Integer stationId, Integer gunId) {
        //1.组织一个和业务数据有关的缓存key值
        String costRuleKey="cost:rule:key:"+stationId+":"+gunId;
        //2.读取的是list redis缓存也是用list结构
        ListOperations<String,CostRulePO> opsForList = redisTemplate.opsForList();
        //3.判断存在 命中 exists
        Boolean exists = redisTemplate.hasKey(costRuleKey);
        if(!exists){
            log.info("没命中数据,key:{}",costRuleKey);
            //没命中读取数据库数据
            //select * from charging_cost_rule where station_id=#{} and gun_type=#{}
            QueryWrapper<CostRulePO> queryWrapper=new QueryWrapper<>();
            queryWrapper.eq("station_id",stationId).eq("gun_type",gunId);
            List<CostRulePO> pos = costRuleMapper.selectList(queryWrapper);
            //存储到缓存
            opsForList.leftPushAll(costRuleKey,pos);
            return pos;
        }else{
            List<CostRulePO> range = opsForList.range(costRuleKey, 0, -1);
            log.info("命中了数据:{},key:{}",range,costRuleKey);
            //命中直接读取缓存
            return range;
        }
    }
}
